﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using CoreEx.Common.Data;
using CoreEx.Common.Implementation.Data;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC.Configuration;
namespace CoreEx.MicroMapper.Implementation
{
    [Implements(typeof(IMicroMapper<IDataRecord,IRow>))]
    public class DataRowToRowMapper : MicroMapper<IDataRecord,IRow>
    {
        private readonly ITable _table;

        public DataRowToRowMapper(ITable table)
        {
            _table = table;
        }

        public override void Initialize(IServiceContainer source)
        {
            base.Initialize(source);

            SourceAccessorSelector = (dataRecord) => _table.Columns.Values.Select
                (c => (IAccessorInfo)new AccessorInfo { Name = c.ColumnName, DataType = c.DataType });

            TargetAccessorSelector = (dataRecord) => _table.Columns.Values.Select
                (c => (IAccessorInfo)new AccessorInfo { Name = c.ColumnName, DataType = c.DataType });


            SourceAccessor = (accessorInfo, dataRecord) => dataRecord[accessorInfo.Name];

            TargetFactory = (container =>
                                 {
                                     var row = new Row();
                                     row.Table = _table;
                                     return row;
                                 });


            TargetAccessor = (accessorInfo, row, value) =>
                                 {
                                     var cell = new Cell();
                                     cell.Row = row;
                                     cell.Column = _table.Columns[accessorInfo.Name];
                                     cell.Value = value;
                                     row.Cells.Add(accessorInfo.Name, cell);
                                 };
            

        }
    }
}
